package cn.gxufe.reliable.message.api.service.impl;

import cn.gxufe.reliable.message.api.holder.MessageHolder;
import cn.gxufe.reliable.message.api.service.CompensableMessage;
import cn.gxufe.reliable.message.common.Message;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author yingjie.rong
 **/
public class CompensableMessageImpl implements CompensableMessage {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private ObjectMapper objectMapper =  new ObjectMapper();
    private String updateSql = "update reliable_message set `other` = ? where `key` = ? ";

    @Override
    @Transactional(rollbackFor = Throwable.class,propagation = Propagation.MANDATORY)
    public void set(String key, String value) {
        Message message = MessageHolder.getMessage();
        if( message != null ){
            jdbcTemplate.update( updateSql, getOther(),message.getKey());
        } else {
            MessageHolder.setValue(key,value);
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class,propagation = Propagation.MANDATORY)
    public String getValue(String key) {
        Map<String, String> map = MessageHolder.getMap();
        return map.get(key);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class,propagation = Propagation.MANDATORY)
    public Message getMessage() {
        return MessageHolder.getMessage();
    }

    private String getOther(){
        try {
            return objectMapper.writeValueAsString(MessageHolder.getMap());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
